import { Behaviour, GameObject, Transform, SpriteRenderer, isEditorMode, SerilizeField, propertyEditor_None, ids, getImage, propertyEditor_Number } from "../gameengine";
import { core } from "../gameengine";
import { itemPrefab } from "../prefab";
import { ItemConfigType, itemConfig } from "../config";
import { user } from "../user";
import { Rect_Collider } from "../collider/rect_Collider";
import { ConversationTest } from "../conversation/conversationTest";
import { gameEventBus } from "../GameEventBus";
import { marshal, MarshalConRoomAState, MarshalConRoomBState, MarshalDeadHouseState, MarshalHallState, MarshalHallwayF1State, MarshalHallwayF2State, MarshalOfficeState, MarshalWardAState, MarshalWardBState, MarshalWardCState, MarshalWcManState, MarshalGateState } from "../marshal";
import { lock } from "../lock/Lock";
import { music } from "../music/music";

const items: GameObject[] = [];

/**
 * 这一脚本用来创建场景中的物品
 */

export class ItemLayerBehaviour extends Behaviour {


    // private items: GameObject[] = [];

    // @SerilizeField(propertyEditor_None)
    // isFront: boolean = false;

    @SerilizeField(propertyEditor_None)
    private itemData: any[];

    onStart() {

        if (!isEditorMode()) {
            for (let itemData of this.itemData) {
                const itemGameObject = core.createPrefab(itemPrefab);
                //设定坐标
                const itemTransform = itemGameObject.getScript(Transform);
                itemTransform.x = itemData.x * 64;
                itemTransform.y = itemData.y * 64;
                //设定物品id
                itemGameObject.id = itemData.uID;
                //挂载ItemBehaviour脚本
                const itemBehaviour = new ItemBehaviour();
                itemBehaviour.uID = itemData.uID;   //物品自己独一份id （唯一属性，独一份的线索）
                //物品的各种判断属性
                itemBehaviour.canTalk = itemData.canTalk;
                itemBehaviour.clue = itemData.clue;
                itemBehaviour.canPick = itemData.canPick;
                itemBehaviour.key = itemData.key;
                itemBehaviour.isHiddenClue = itemData.isHiddenClue;
                itemBehaviour.isDoor = itemData.isDoor;
                itemBehaviour.isDisappear = itemData.isDisappear;
                itemBehaviour.isLocked = itemData.isLocked;
                itemBehaviour.doorSceneID = itemData.doorSceneID;
                itemBehaviour.config = itemConfig.find(config => config.id === itemData.cID);
                itemGameObject.addScript(itemBehaviour);
                // console.log(itemBehaviour);
                //设置物品图片
                const spriteRenderer = itemGameObject.getScript(SpriteRenderer);
                spriteRenderer.imageName = itemBehaviour.config.iconName;
                //把item当作children放入ItemLayer下面
                this.displayObject.addChild(itemGameObject);
                ids[itemData.uID] = itemGameObject; //把这个id加进去以便后面使用getGameObjectById

                // console.log(images);
                items.push(itemGameObject);

            }
            // console.log(this.displayObject);
        }


    }

    onUpdate() {
    }
}

/**
 * 这一脚本用来设置物体需要进行的操作
 * 物品具有的属性：
 * 1. uID 物品的唯一属性 多为物品名字
 * 2. cID 贴图属性 对应config里面的id
 * 3. x,y 位置属性
 * 4. canPick 可拾取的判断
 * 5. key 拾取的物体
 * 6. canTalk 可对话的判断
 * 7. clue触发特殊对话的线索
 * 8. isDoor 判断是否为门
 * 9. isDisappear 判断是否需要获取完物品消失
 * 10. isLocked 判断门是否关着
 * 11. doorSceneID 记录门对应的场景ID
 * 12. isReduceMind 判断是否减少精神值
 */

export class ItemBehaviour extends Behaviour {


    uID: string;

    config: ItemConfigType;

    canPick: boolean = false;       //默认不能拾取
    key: string;                    //记录拾取的物品
    canTalk: boolean = false;       //默认不可以对话
    clue: string;                   //触发特殊对话的条件线索
    isHiddenClue: boolean = false;   //默认不是特殊线索
    isDoor: boolean = false;        //默认不是门
    isDisappear: boolean = false;   //默认物体不会消失
    isLocked: boolean = false;      //默认门是开着的
    doorSceneID: number = -1;       //默认为查找不到的-1

    protected onStart() {
        //添加item的碰撞盒
        // console.log("开始ItemBehaviour")
        const itemCollider = new Rect_Collider();
        setTimeout(() => {
            itemCollider.width = getImage(this.config.iconName).width;
            itemCollider.height = getImage(this.config.iconName).height;
            itemCollider.x = 0;
            itemCollider.y = 0;
            itemCollider.type = 2;
            itemCollider.canTalk = this.canTalk;
            itemCollider.clue = this.clue;
            itemCollider.canPick = this.canPick;
            itemCollider.key = this.key;
            itemCollider.isDoor = this.isDoor;
            itemCollider.isLocked = this.isLocked;
            itemCollider.doorSceneID = this.doorSceneID;
            itemCollider.isHiddenClue = this.isHiddenClue;
            itemCollider.isDisappear = this.isDisappear;
            this.displayObject.addScript(itemCollider);

            // console.log(itemCollider);

        }, 1000);

        //可对话的物体添加ConversationTest脚本
        if (this.canTalk == true) {
            const conversation = new ConversationTest();
            this.displayObject.addScript(conversation);

        }
        //可拾取的物体添加pickItemBehaviour脚本
        if (this.canPick == true) {
            const pickItemBehaviour = new PickItemBehaviour();
            pickItemBehaviour.isDisappear = this.isDisappear;
            pickItemBehaviour.isHiddenClue = this.isHiddenClue;
            this.displayObject.addScript(pickItemBehaviour);
        }
        //门添加DoorBehaviour脚本
        if (this.isDoor == true) {
            const doorBehaviour = new DoorBehaviour();
            doorBehaviour.isLocked = this.isLocked;
            doorBehaviour.doorSceneID = this.doorSceneID;
            doorBehaviour.doorItemkey = this.key;
            this.displayObject.addScript(doorBehaviour);
        }
        //添加HiddClueBehaviour脚本
        if (this.isHiddenClue == true) {
            const hiddenClueBehaviour = new HiddenClueBehaviour();
            hiddenClueBehaviour.isHiddenClue = this.isHiddenClue;
            hiddenClueBehaviour.isDisappear = this.isDisappear;
            this.displayObject.addScript(hiddenClueBehaviour);
        }
        if (this.isDisappear == true) {
            const disappearBehaviour = new DisappearBehaviour();
            this.displayObject.addScript(disappearBehaviour);
        }

        // console.log(this.displayObject);


    }

    protected onUpdate(advancedTime: number) {

    }
}

export class PickItemBehaviour extends Behaviour {

    isDisappear: boolean = false;

    isHiddenClue: boolean = false;

    protected onStart() {

    }

    PickItem() {
        const itemBehaviour = this.displayObject.getScript(ItemBehaviour);
        if (!itemBehaviour) {
            return;
        }
        // console.log("选择物品" + itemBehaviour.key);
        if (itemBehaviour.key != "none") {
            console.log("pickItemBehaviour");
            user.keys.push(itemBehaviour.key);
            console.log(itemBehaviour.key + "放入背包");
            console.log(user.keys);
            //更新任务
            gameEventBus.dispatch("get", itemBehaviour.key);
        }

        if (itemBehaviour.key == "candle1" || itemBehaviour.key == "stone") {
            user.mind += -20;
            console.log(user.mind);
            // music.glassPlay();
        }
        if (user.mind == 60) {
            music.glassPlay();
            music.heartPlay();
        }

        music.getPlay();

        // if(itemBehaviour.)

        // if (this.isDisappear == true) {
        //     const rectCollider = this.displayObject.getScript(Rect_Collider);
        //     rectCollider.onEnd();
        //     this.displayObject.parent.removeChild(this.displayObject);

        // }


        this.displayObject.removeScript(this);
        user.addItemRemoveRecord(this.displayObject.id, this.isDisappear);

    }

    protected onUpdate(advancedTime: number) {

    }
}

export class HiddenClueBehaviour extends Behaviour {

    isHiddenClue: boolean = true;

    isDisappear: boolean = false;

    protected onStart() {
        user.hiddenClueItemRecord.push(this.displayObject.id);
        console.log("隐藏线索对应的物品：", user.hiddenClueItemRecord);
    }
    protected onUpdate(advancedTime: number) {
    }

    PickItem() {
        const itemBehaviour = this.displayObject.getScript(ItemBehaviour);
        if (!itemBehaviour) {
            return;
        }
        // console.log("选择物品" + itemBehaviour.key);

        if (this.isHiddenClue == false) {
            console.log("HiddenClueBehaviour");

            if (itemBehaviour.key != "none") {
                user.keys.push(itemBehaviour.key);
                console.log(itemBehaviour.key + "放入背包");
                console.log(user.keys);
                //更新任务
                gameEventBus.dispatch("get", itemBehaviour.key);
                user.mind += -20;
                console.log(user.mind);
                music.getPlay();
            }


            if (user.mind == 20) {
                music.heartPlay();
            }
            if (user.mind == 0) {
                music.heartPlay();
            }

            // const conversation = new ConversationTest();
            // this.displayObject.addScript(conversation);
            // itemBehaviour.canTalk = true;

        }

        // if(itemBehaviour.)

        // if (this.isDisappear == true) {
        //     const rectCollider = this.displayObject.getScript(Rect_Collider);
        //     rectCollider.onEnd();
        //     this.displayObject.parent.removeChild(this.displayObject);

        // }

        this.displayObject.removeScript(this);
        user.addItemRemoveRecord(this.displayObject.id, this.isDisappear);

    }


}

export class DoorBehaviour extends Behaviour {

    @SerilizeField(propertyEditor_None)
    isLocked: boolean = false;

    @SerilizeField(propertyEditor_Number)
    doorSceneID: number = -1;

    doorItemkey: string;

    doorScene: string[] = [
        "assets/scene/conRoomA.scene.json",         // 0，诊室A
        "assets/scene/conRoomB.scene.json",         // 1，诊室B
        "assets/scene/deadHouse.scene.json",        // 2，太平间
        "assets/scene/hall.scene.json",             // 3，等候大厅
        "assets/scene/hallwayF1.scene.json",        // 4，一层走廊
        "assets/scene/hallwayF2.scene.json",        // 5，二层走廊
        "assets/scene/office.scene.json",           // 6，办公室
        "assets/scene/wardA.scene.json",            // 7，病房A
        "assets/scene/wardB.scene.json",            // 8，病房B
        "assets/scene/wardC.scene.json",            // 9，病房C
        "assets/scene/wcMan.scene.json",            // 10，男厕所
        "assets/scene/wcWoman.scene.json",          // 11，女厕所
    ]


    protected onStart() {
        // this.searchKeys("knife");

    }


    searchKeys(doorkey: string) {
        const conversationTest = this.displayObject.getScript(ConversationTest);
        if (user.keys.length < 1) {
            console.log("背包是空的当然没钥匙啦");
            // this.changeConversationState(1);
            if (conversationTest) {
                conversationTest.searchKeys(doorkey);
            }

        }
        for (let key of user.keys) {
            if (key == doorkey) {
                console.log("已获取相应钥匙");
                this.isLocked = false;
                if (conversationTest) {
                    conversationTest.searchKeys(doorkey);
                }
                // this.changeConversationState(2);
                // const conversationTest = this.displayObject.getScript(ConversationTest);
                // conversationTest.ChangeState('keyClue');
                // console.log(conversationTest);
            } else {
                // const conversationTest = this.displayObject.getScript(ConversationTest);
                // conversationTest.ChangeState('normal');
                console.log("未获取相应钥匙");
            }
        }
        if (this.doorItemkey == "mimasuo") {

            if (this.displayObject.id == "door3") {
                lock.lockInstantiate(0);
            }
            if (this.displayObject.id == "door_ward2") {
                lock.lockInstantiate(1);
            }
            if (this.displayObject.id == "door_ward3") {
                lock.lockInstantiate(2);
            }

            lock.pass = () => {
                this.isLocked = false;
                console.log("锁开了");
            };
            lock.failed = () => {
                this.isLocked = true;
                console.log("密码错了");

            }

        }
    }

    ChangeScene() {
        // const doorSceneID = this.displayObject.getScript(ItemBehaviour).doorSceneID;
        if (this.isLocked == false) {
            console.log('切换场景');
            music.doorPlay();
            switch (this.doorSceneID) {
                case 0:
                    marshal.changeState(new MarshalConRoomAState());
                    user.addSceneRecord(this.doorScene[0]);
                    break;
                case 1:
                    marshal.changeState(new MarshalConRoomBState());
                    user.addSceneRecord(this.doorScene[1]);
                    break;
                case 2:
                    marshal.changeState(new MarshalDeadHouseState());
                    user.addSceneRecord(this.doorScene[2]);
                    break;
                case 3:
                    marshal.changeState(new MarshalHallState());
                    user.addSceneRecord(this.doorScene[3]);
                    break;
                case 4:
                    marshal.changeState(new MarshalHallwayF1State());
                    user.addSceneRecord(this.doorScene[4]);
                    break;
                case 5:
                    marshal.changeState(new MarshalHallwayF2State());
                    user.addSceneRecord(this.doorScene[5]);
                    break;
                case 6:
                    marshal.changeState(new MarshalOfficeState());
                    user.addSceneRecord(this.doorScene[6]);
                    break;
                case 7:
                    marshal.changeState(new MarshalWardAState());
                    user.addSceneRecord(this.doorScene[7]);
                    break;
                case 8:
                    marshal.changeState(new MarshalWardBState());
                    user.addSceneRecord(this.doorScene[8]);
                    break;
                case 9:
                    marshal.changeState(new MarshalWardCState());
                    user.addSceneRecord(this.doorScene[9]);
                    break;
                case 10:
                    marshal.changeState(new MarshalWcManState());
                    user.addSceneRecord(this.doorScene[10]);
                    break;
                case 11:
                    marshal.changeState(new MarshalGateState());
                    user.addSceneRecord(this.doorScene[11]);
                    break;

            }
        } else {
            console.log("门锁上了");
        }
    }

    protected onUpdate(advancedTime: number) {

    }


}

export class DisappearBehaviour extends Behaviour {


    protected onStart() {

    }

    protected onUpdate(advancedTime: number) {

    }

    RemoveItem() {
        const rectCollider = this.displayObject.getScript(Rect_Collider);
        rectCollider.onEnd();
        this.displayObject.parent.removeChild(this.displayObject);
    }


}
